import React, { Component } from 'react'
import { BrowserRouter as Routers,  Route, Switch, Redirect} from 'react-router-dom'
import cookie from 'js-cookie'
import routes from './route'
import FirstRegister from '../pages/first_register/register'
import { _checkLogin } from '../apis/home'

const NotFoundRedirect = () => <Redirect to='/404' />
let token = cookie.get('token')
let pathname = window.location.pathname
class Router extends Component {
    constructor(props) {
        super(props)
        this.state = {
           loginStatus:  token !== '' && token !== undefined ? true : false
        }
    }
    async componentDidMount() {
        if (this.state.loginStatus) {
            const data = await _checkLogin({token: token})
            if (data && data.status === 'success') {
                if (data.result.loginStatus !== 'on') {
                    this.setState({loginStatus: false})
                } else {
                    this.setState({loginStatus: true})
                }
            } else {
                this.setState({loginStatus: false})
            }
        }
    }

    render() {

    return (
      <Routers basename={'/home'}>
          { this.state.loginStatus ?
            <Switch >
              {
                routes.map(({ name, path, exact = true, component }) => (
                  <Route path = {path} exact={exact} component={component} key={name} />
                ))
              }
                <Route component={NotFoundRedirect} />
            </Switch> :
              
              pathname.indexOf('protocal') > -1 || pathname.indexOf('commitment') > -1 ? 

              <Switch >
              </Switch>

              :
              
              <Switch >
                <Route component={FirstRegister} />
              </Switch>
              
              
          }
      </Routers>
    );
  }
}

export default Router;
